package com.lxdp.controller;


import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxdp.dto.Result;
import com.lxdp.dto.UserDTO;
import com.lxdp.entity.Blog;
import com.lxdp.entity.User;
import com.lxdp.service.IBlogService;
import com.lxdp.service.IUserService;
import com.lxdp.utils.RedisConstants;
import com.lxdp.utils.SystemConstants;
import com.lxdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hong
 * @since 2023-04-22
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        // 获取登录用户
        // 返回id
        return blogService.saveBlog(blog);
    }

    @GetMapping("/of/user")
    public Result queryBlogByUserId(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam("id") Long id) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        // 修改点赞数量
        return blogService.likeBlog(id);
    }

    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        records.forEach(this::isLiked);
        return Result.ok(records);
    }

    @GetMapping("/likes/{id}")
    public Result queryLikes(@PathVariable Long id) {
        return blogService.queryLikes(id);
    }

    @GetMapping("/{id}")
    public Result blogDetail(@PathVariable Long id) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("user 不存在");
        }
        String name = user.getNickName();
        if (name == null) {
            return Result.fail("name 不存在");
        }
        String icon = user.getIcon();
        if (icon == null) {
            return Result.fail("icon 不存在");
        }
        Blog blog = blogService.getById(id);
        blog.setIcon(icon);
        blog.setName(name);
        isLiked(blog);
        if (blog == null) {
            return Result.fail("blog 不存在");
        }
        // 根据用户查询
        return Result.ok(blog);
    }

    private void isLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        Long id = user.getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), id.toString());
        blog.setIsLike(BooleanUtil.isTrue(score != null));
    }

    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        return Result.ok(records);
    }

    @GetMapping("/of/follow")
    public Result queryBlogFollow(@RequestParam("lastId") Long max,@RequestParam(value = "offset",defaultValue = "0")Integer offset){
        return blogService.queryBlogFollow(max,offset);
    }
}
